import sys
import time
import requests
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QTextEdit, QWidget
from PyQt6.QtCore import QThread, pyqtSignal, QTimer

# 爬虫线程类
class SpiderThread(QThread):
    # 定义一个信号，用于传递爬取到的数据
    data_signal = pyqtSignal(str)

    def __init__(self, interval=5):
        super().__init__()
        self.interval = interval  # 爬虫间隔时间（秒）
        self.running = True

    def run(self):
        url = "https://www.baidu.com"
        while self.running:
            try:
                response = requests.get(url)
                if response.status_code == 200:
                    data = response.text[:100]  # 示例：只取前100个字符
                    self.data_signal.emit(data)  # 发送信号
                else:
                    self.data_signal.emit("Failed to fetch data")
            except Exception as e:
                self.data_signal.emit(f"Error: {str(e)}")
            time.sleep(self.interval)  # 等待指定时间

    def stop(self):
        self.running = False

# 主窗口类
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 设置窗口布局
        self.setWindowTitle("PyQt6 Spider Example")
        self.setGeometry(100, 100, 400, 300)

        # 文本框用于显示爬取到的数据
        self.text_edit = QTextEdit(self)
        self.text_edit.setReadOnly(True)

        # 按钮用于停止爬虫
        self.stop_button = QPushButton("Stop Spider", self)
        self.stop_button.clicked.connect(self.stop_spider)

        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.text_edit)
        layout.addWidget(self.stop_button)

        # 设置中央窗口
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # 创建爬虫线程
        self.spider_thread = SpiderThread(interval=5)  # 每5秒爬取一次
        self.spider_thread.data_signal.connect(self.update_text_edit)  # 连接信号到槽函数
        self.spider_thread.start()  # 启动爬虫线程

    def update_text_edit(self, data):
        # 更新文本框内容
        # self.text_edit.append(data)
        data2 = self.text_edit.toPlainText()
        data += data2
        self.text_edit.setPlainText(data)

    def stop_spider(self):
        # 停止爬虫线程
        self.spider_thread.stop()
        self.stop_button.setEnabled(False)  # 禁用按钮

    def closeEvent(self, event):
        # 窗口关闭时停止爬虫线程
        if hasattr(self, "spider_thread"):
            self.spider_thread.stop()
            self.spider_thread.wait()
        event.accept()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
